package com.qianya.oa.util;


import com.qianya.oa.vo.UploadFileRespVo;
import com.qianya.oa.mapper.UploadFileRespMapper;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.stream.Stream;

@Slf4j
@Service
public class UploadServiceImpl implements UploadService {

    @Resource
    private FileService fileService;
    @Resource
    private UploadFileRespMapper uploadFileRespMapper;


    /**
     * 保存单个文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public CommonResult<UploadFileRespVo> saveImgFile(MultipartFile file) throws IOException {
        if (file.getSize() <= 0) {
            return CommonResult.erro("文件不能为空");
        }
        if (file.getSize() > 1024 * 1000 * 5) {
            return CommonResult.erro("图片大小不能超过5MB");
        }
        String originalFilename = file.getOriginalFilename();
        String ext = FilenameUtils.getExtension(originalFilename);
        if (ext == null || isAllowImg(originalFilename)) {
            return CommonResult.erro("文件格式需为图片（gif,jpg,jpeg,png,ico,webp,bmp）");
        }
        String newFileName = FileService.getFileName(null, ext);
        UploadFileRespVo uploadFileRespDto = fileService.saveImg(newFileName, file);
        log.info("上传单文件，响应{}", uploadFileRespDto);
        return CommonResult.success(uploadFileRespDto);
    }

    @Override
    public CommonResult<UploadFileRespVo> saveVideoFile(MultipartFile file) throws IOException {
        if (file.getSize() <= 0) {
            return CommonResult.erro("文件不能为空");
        }
        if (file.getSize() > 1024 * 1000 * 50) {
            return CommonResult.erro("视频大小不能超过50MB");
        }
        String originalFilename = file.getOriginalFilename();
        String ext = FilenameUtils.getExtension(originalFilename);
        String newFileName = FileService.getFileName(null, ext);
        UploadFileRespVo uploadFileRespDto = fileService.saveVideo(newFileName, file);
        log.info("上传单文件，响应{}", uploadFileRespDto);
        return CommonResult.success(uploadFileRespDto);
    }

    @Override
    public CommonResult<UploadFileRespVo> saveMP3File(MultipartFile file) throws IOException {
        if (file.getSize() <= 0) {
            return CommonResult.erro("文件不能为空");
        }
        if (file.getSize() > 1024 * 1000 * 30) {
            return CommonResult.erro("音频大小不能超过30MB");
        }
        String originalFilename = file.getOriginalFilename();
        String ext = FilenameUtils.getExtension(originalFilename);
        if (ext == null || !ext.toLowerCase().equals("mp3")) {
            return CommonResult.erro("文件格式需为mp3");
        }
        String newFileName = FileService.getFileName(null, ext);
        UploadFileRespVo uploadFileRespDto = fileService.saveMP3(newFileName, file);
        log.info("上传单文件，响应{}", uploadFileRespDto);
        return CommonResult.success(uploadFileRespDto);
    }


    @Override
    public CommonResult<UploadFileRespVo> saveFile(MultipartFile file,Long userId) throws IOException {
        if (file.getSize() <= 0) {
            return CommonResult.erro("文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        String ext = FilenameUtils.getExtension(originalFilename);
        String newFileName = FileService.getFileName(null, ext);
        UploadFileRespVo uploadFileRespDto = fileService.saveMP3(newFileName, file);
        uploadFileRespDto.setCreateTime(new Date());
        log.info("上传单文件，响应{}", uploadFileRespDto);
        int i = uploadFileRespMapper.InsertFile(uploadFileRespDto.getUrl(), uploadFileRespDto.getOriginalFileName(), uploadFileRespDto.getFileName(),uploadFileRespDto.getCreateTime(),null, Math.toIntExact(userId));
        if (i == 0){
         throw  new IOException("保存导数据库失败");
        }
            return CommonResult.success(uploadFileRespDto);
    }

    /**
     * 判断是否为 gif,jpg,jpeg,png,ico,webp,bmp
     *
     * @param ext
     * @return
     */
    public static boolean isAllowImg(String ext) {
        return Stream.of("gif", "jpg", "jpeg", "png", "ico", "webp", "bmp").anyMatch(e -> e.equals(ext.toLowerCase()));
    }


    /**
     * 压缩图片并存储，指定大小
     *
     * @param inputStream
     * @param path
     * @return
     * @throws IOException
     */
    private static String uploadCompress(InputStream inputStream, String path, int size1, int size2) throws IOException {
        Thumbnails.of(inputStream).size(size1, size2).toFile(path);
        return path;
    }
}
